package com.example.pclimb.ui.requests;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityCreateRequestBinding;
import com.example.pclimb.model.ClimbRequest;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.ClimbRequestViewModel;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 创建陪爬申请的活动
 */
public class CreateRequestActivity extends AppCompatActivity {

    private ActivityCreateRequestBinding binding;
    private ClimbRequestViewModel viewModel;
    private Date selectedDate;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCreateRequestBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ClimbRequestViewModel.class);

        // 设置工具栏导航
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 设置日期选择按钮点击事件
        binding.btnSelectDate.setOnClickListener(v -> showDatePicker());

        // 设置提交按钮点击事件
        binding.btnSubmit.setOnClickListener(v -> submitRequest());
    }

    /**
     * 显示日期选择对话框
     */
    private void showDatePicker() {
        // 获取当前日期
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // 创建日期选择对话框
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    // 设置所选日期
                    Calendar selectedCalendar = Calendar.getInstance();
                    selectedCalendar.set(selectedYear, selectedMonth, selectedDay);
                    selectedDate = selectedCalendar.getTime();

                    // 更新UI显示所选日期
                    binding.tvSelectedDate.setText(dateFormat.format(selectedDate));
                },
                year,
                month,
                day);

        // 设置最小日期为今天
        datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());

        // 显示对话框
        datePickerDialog.show();
    }

    /**
     * 提交陪爬申请
     */
    private void submitRequest() {
        // 重置错误提示
        binding.tilLocation.setError(null);
        binding.tilPeopleCount.setError(null);
        binding.tilBudget.setError(null);
        binding.tilRequirements.setError(null);

        // 获取输入值
        String location = binding.etLocation.getText().toString().trim();
        String peopleCountStr = binding.etPeopleCount.getText().toString().trim();
        String budgetStr = binding.etBudget.getText().toString().trim();
        String requirements = binding.etRequirements.getText().toString().trim();

        // 验证输入
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(requirements)) {
            binding.tilRequirements.setError(getString(R.string.error_field_required));
            focusView = binding.etRequirements;
            cancel = true;
        }

        if (TextUtils.isEmpty(peopleCountStr)) {
            binding.tilPeopleCount.setError(getString(R.string.error_field_required));
            focusView = binding.etPeopleCount;
            cancel = true;
        }

        if (TextUtils.isEmpty(budgetStr)) {
            binding.tilBudget.setError(getString(R.string.error_field_required));
            focusView = binding.etBudget;
            cancel = true;
        }

        if (TextUtils.isEmpty(location)) {
            binding.tilLocation.setError(getString(R.string.error_field_required));
            focusView = binding.etLocation;
            cancel = true;
        }

        if (selectedDate == null) {
            Toast.makeText(this, R.string.error_select_date, Toast.LENGTH_SHORT).show();
            cancel = true;
        }

        if (cancel) {
            // 输入有误，聚焦到错误输入框
            if (focusView != null) {
                focusView.requestFocus();
            }
        } else {
            // 显示进度条
            showProgress(true);

            // 创建陪爬申请
            int userId = SharedPreferencesUtil.getUserId(this);
            Date requestDate = new Date(); // 当前日期为申请日期
            int peopleCount = Integer.parseInt(peopleCountStr);
            double budget = Double.parseDouble(budgetStr);

            ClimbRequest request = new ClimbRequest(
                    userId,
                    location,
                    requestDate,
                    selectedDate,
                    peopleCount,
                    requirements,
                    budget
            );

            // 提交申请
            viewModel.insert(request, id -> {
                // 使用runOnUiThread确保UI更新在主线程中执行
                runOnUiThread(() -> {
                    showProgress(false);
                    if (id > 0) {
                        // 提交成功
                        Toast.makeText(CreateRequestActivity.this, R.string.request_submitted, Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 提交失败
                        Toast.makeText(CreateRequestActivity.this, R.string.request_submission_failed, Toast.LENGTH_SHORT).show();
                    }
                });
            });
        }
    }

    /**
     * 显示或隐藏进度条
     */
    private void showProgress(boolean show) {
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.btnSubmit.setEnabled(!show);
        binding.etLocation.setEnabled(!show);
        binding.etPeopleCount.setEnabled(!show);
        binding.etBudget.setEnabled(!show);
        binding.etRequirements.setEnabled(!show);
        binding.btnSelectDate.setEnabled(!show);
    }
} 